package com.ktjiaoyu.service.impl;

import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.mapper.SysRoleMapper;
import com.ktjiaoyu.service.SysRoleService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @return 13141
 * 2025/7/3
 * 10:00
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SysRoleServiceImpl.class);
    @Resource
    private SysRoleMapper sysRoleMapper;

    @Override
    public List<SysRole> findAll() throws Exception {
        try {
            return sysRoleMapper.getAll();
        } catch (Exception e) {
            LOGGER.error("执行SysRoleServiceImpl.findAll()方法出现异常." ,e);
            throw e;
        }
    }

    /**
     * 新增 修改
     * @param entity
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public boolean saveOrUPdate(SysRole entity) throws Exception {
        try {
            if (entity.getId() == null) {
//                无主题则新增
                return sysRoleMapper.insert(entity) > 0;
            } else {
//                有主题则修改
                return sysRoleMapper.update(entity) > 0;
            }
        } catch (Exception e) {
            LOGGER.error("执行 SysRoleServiceImpl.saveOrUpdate(SysRole)方法出现异常，", e);
            throw e;
        }
    }

    @Override
    public SysRole findByCode(String code) throws Exception {
        try {
            return sysRoleMapper.getByCode(code);
        } catch (Exception e) {
            LOGGER.error("执行 findByCode()方法出现异常", e);
            throw e;
        }
    }

    @Transactional
    @Override
    public SysRole getById(Long id) throws Exception {
        try {
            return sysRoleMapper.getById(id);
        } catch (Exception e) {
            LOGGER.error("执行SysRoleServiceImpl.getById(Integer)方法出现异常.", e);
            throw e;
        }
    }
    @Transactional
    @Override
    public int delete(Long id) throws Exception {
        try {
            Long count = sysRoleMapper.getByRoleName(id); // 判断角色下是否有用户
            if (count == 0) {
                return sysRoleMapper.delete(id);
            }else {
                return 501;
            }
        }catch (Exception e){
            LOGGER.error("执行SysRoleServiceImpl.delete(Integer)方法出现异常.", e);
            throw e;
        }
    }
}
